﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SnippetBox.Core.Common.Extensions;
using SnippetBox.Core.Common.Text;
using SnippetBox.Core.Infrastructure;

namespace SnippetBox.Core.Data.Models {
    public class Snippet : IDeletable {
        public Snippet(string title, string bodyRaw, Category category, User author) {
            Title = title;
            Slug = title.Slugify();
            BodyRaw = bodyRaw;
            Category = category;
            Author = author;
            DateCreated = DateTime.Now;
            DateEdited = DateTime.Now;
            
            Markdown m = new Markdown();
            Body = m.Transform(bodyRaw);
        }

        public Snippet() {}

        public int SnippetId { get; set; }
        [Required, MaxLength(200)]
        public string Title { get; set; }
        [MaxLength(200)]
        public string Slug { get; set; }
        [Required, AllowHtml, MaxLength(Int32.MaxValue)]
        public string BodyRaw { get; set; }
        [AllowHtml, MaxLength(Int32.MaxValue)]
        public string Body { get; set; }
        public int Views { get; set; }
        public int Favorited { get; set; }
        [UIHint("RelativeDate")]
        public DateTime DateCreated { get; set; }
        public DateTime DateEdited { get; set; }
        public virtual Category Category { get; set; }
        [UIHint("UserLink"), Column("UserId")]
        public virtual User Author { get; set; }
        public bool IsDeleted { get; set; }

        public virtual ICollection<User> UsersFavorited { get; set; }

        public string Link {
            get {
                UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
                return url.RouteUrl("Snippet-Details", new {
                                                                categoryId = Category.CategoryId, 
                                                                categorySlug = Category.Slug, 
                                                                snippetId = SnippetId, 
                                                                snippetSlug = Slug
                                                            });
            }
        }
        
        public bool UserHasFavorited(string username = null) {
            if (username == null)
                username = HttpContext.Current.User.Identity.Name;
            return UsersFavorited.Any(x => x.Username == username);
        }

        public bool CanEdit(User user) {
            if (user == null)
                return false;
            
            if (user.Role == Role.Member)
                return Settings.Current.Permissions.AllowMembersToCreateSnippets && Author.UserId == user.UserId;

            return user.IsInRole(Role.Editor);
        }

    }
}
